package c_008;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用reentrandlock可以进行"尝试锁定"tryLock
 */
public class T03_ReentrantLock1 {

    Lock lock = new ReentrantLock();    //可以替代synchronized

    void m1(){
        try{
            lock.lock();    //synchronized(this)
            for(int i = 0; i < 10; i++){
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (Exception e){

        } finally {
            lock.unlock();
        }
    }

    /**
     * 使用tryLock进行尝试锁定,不管锁定与否,方法都将继续执行
     * 可以根据tryLock的返回值来判断是否锁定
     * 也可以指定tryLock的时间
     */
    void m2(){
        boolean locked = false;
        try{
            locked = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2..." + locked);
        }catch (InterruptedException e) {   //没拿到锁不会抛出异常
            e.printStackTrace();
        }finally {
            if(locked) lock.unlock();
        }
    }

    public static void main(String[] args) {
        T03_ReentrantLock1 rl = new T03_ReentrantLock1();
        new Thread(rl::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(rl::m2).start();
    }

}
